package com.leyou.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.RegexUtils;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.UserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY;

/**
 * @author 虎哥
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final StringRedisTemplate redisTemplate;
    private final AmqpTemplate amqpTemplate;
    private final BCryptPasswordEncoder passwordEncoder;

    public UserServiceImpl(StringRedisTemplate redisTemplate, AmqpTemplate amqpTemplate, BCryptPasswordEncoder passwordEncoder) {
        this.redisTemplate = redisTemplate;
        this.amqpTemplate = amqpTemplate;
        this.passwordEncoder = passwordEncoder;
    }

    private static final String KEY_PREFIX = "user:verify:phone:";

    @Override
    public Boolean infoExists(String data, Integer type) {
        // 健壮性判断
        if(type != 1 && type != 2){
            throw new LyException(400, "请求参数有误！");
        }
        // 返回
        return query()
                .eq(type == 1, "username", data)
                .eq(type == 2, "phone", data)
                .count() == 1;
    }

    @Override
    public void sendVerifyCode(String phone) {
        // 1.验证手机号码
        if (!RegexUtils.isPhone(phone)) {
            // 手机号有误
            throw new LyException(400, "手机号码错误！");
        }
        // 2.生成一个随机验证码
        String code = RandomStringUtils.randomNumeric(6);

        // 3.将验证码保存在服务端（要用redis代替session）
        redisTemplate.opsForValue().set(KEY_PREFIX + phone, code, 5, TimeUnit.MINUTES);

        // 4.发送短信，将验证码发送到用户手机（向MQ发送消息）
        Map<String,String> msg = new HashMap<>();
        msg.put("phone", phone);
        msg.put("code", code);
        amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME, VERIFY_CODE_KEY, msg);
    }

    @Override
    @Transactional
    public void register(User user, String code) {
        // 1.验证短信验证码
        String cacheCode = redisTemplate.opsForValue().get(KEY_PREFIX + user.getPhone());
        if(!StringUtils.equals(code, cacheCode)){
            // 用户验证码错误
            throw new LyException(400, "验证码有误！");
        }

        // 3.对密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        // 4.写入数据库
        save(user);
    }

    @Override
    public UserDTO queryUserByUsernameAndPassword(String username, String password) {
        // 根据用户名查询
        User user = query().eq("username", username).one();
        // 验证用户名是否正确
        if (user == null) {
            // 用户名错误
            throw new LyException(400, "用户名错误");
        }
        // 验证密码 1234，$2a$08$YaxG6kC5i.F7ste/91yto.ksad7HaNnbbFws.N56j3EiTKTsLPczy
        if (!passwordEncoder.matches(password, user.getPassword())) {
            // 密码错误
            throw new LyException(400, "密码错误");
        }
        // 验证通过，返回用户
        return new UserDTO(user);
    }
}